package cn.bone.netty02.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by superbone on 2016/9/10.
 */
public class TimeServerHandler extends ChannelHandlerAdapter {

    private int counter;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("服务端出现异常:"+cause.getMessage());
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        /*ByteBuf buf = (ByteBuf)msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        String body = new String(bytes,"UTF-8");*/
        String body = (String)msg;
        counter++;
        System.out.println("服务端接收到消息:"+body+"-->"+counter);
        Date date = new Date();
        String respStr = sdf.format(date)+System.getProperty("line.separator");
        ByteBuf resp = Unpooled.copiedBuffer(respStr.getBytes("UTF-8"));
        ctx.writeAndFlush(resp);
    }
}
